package org.zhadoop.streaming.application;

import java.lang.reflect.Constructor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zhadoop.streaming.config.StreamingConfig;
import org.zhadoop.streaming.exception.ErrorCode;
import org.zhadoop.streaming.exception.StreamingException;

/**
 * 创建应用程序的工厂类
 * 完成Application 和底层storm 平台的解耦
 * @author zwd
 *
 */
public class ApplicationFactory {
	private static final Logger LOG = LoggerFactory.getLogger(ApplicationFactory.class);
	
	/**
	 * 创建应用程序
	 * @param conf
	 * @param name
	 * @return
	 */
	public static Application createApplication(StreamingConfig conf,String name) throws StreamingException{
		String appClassName = conf.getStringValue(StreamingConfig.STREAMING_ADAPTOR_APPLICATION);
		
		try{
			Class<?> appClass = Class.forName(appClassName);
			Constructor<?> constructor = appClass.getConstructor(StreamingConfig.class,String.class);
			return (Application) constructor.newInstance(conf,name);
			
		}catch(Exception e){
			if(e instanceof StreamingException){
				throw (StreamingException)e;
			}
			
			StreamingException exception = new StreamingException(e, ErrorCode.UNKNOWN_SERVER_COMMON_ERROR);
            LOG.error(ErrorCode.UNKNOWN_SERVER_COMMON_ERROR.getFullMessage(), e);
            throw exception;
		}
		
	}
}
